import Config
from pynput import keyboard
import time
import MyUtil
import Recorder
import Counter
import threading


def on_press(key):
    try:
        key = str(key).replace('Key.', '').lower()
        # 获取当前时间戳
        timestamp = time.time()

        # 判断按键是否已经松开，没有松开不重复记录
        if key in Config.KEY_STATUS_BUCKET:
            return
        # 记录按键状态到 key_status_bucket
        Config.KEY_STATUS_BUCKET.add(key)

        # 将按键记录添加到缓冲列表
        Config.WRITE_TO_RECORD_BUCKET_BUFFER.append(f"{MyUtil.get_timestamp_remove_yyyymmdd(timestamp)},{key}\n")
        # 如果记录桶中的记录达到阈值，主动写入文件
        if len(Config.WRITE_TO_RECORD_BUCKET_BUFFER) >= Config.WRITE_TO_FILE_STEP:
            MyUtil.loger(f"主动写入记录触发，写入数量为{len(Config.WRITE_TO_RECORD_BUCKET_BUFFER)}")
            Recorder.active_recorder()

    except AttributeError:
        # 处理特殊键
        pass


"""
处理按键按下并弹起之后删除key_status_bucket记录key值
"""
def on_release(key):
    try:
        key = str(key).replace('Key.', '').lower()
        if key in Config.KEY_STATUS_BUCKET:
            Config.KEY_STATUS_BUCKET.remove(key)
    except AttributeError:
        # 处理特殊键
        pass
    except Exception as e:
        MyUtil.loger(f"An error occurred: {e}")


def main():
    # 注册被动记录器
    threading.Thread(target=Recorder.passive_recorder).start()
    # 注册定时counter触发器
    threading.Thread(target=Counter.init).start()
    # 注册键盘事件监听器
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        MyUtil.loger(f'键盘事件监听器注册成功')
        listener.join()


if __name__ == "__main__":
    main()
